<?php

/**
*@作者:MissZhang
*@邮箱:<787727147@qq.com>
*@创建时间:2021/8/13 下午4:30
*@说明:积分商品模型
*/
namespace app\common\model;


use think\facade\Db;
use think\Model;

class JifenGoods extends Model
{
    protected $pk = "goods_id";
    // 定义时间戳字段名
    protected $createTime = 'add_time';
    //修改format类型
    protected $dateFormat = "Y-m-d H:i:s";
    protected $type=[
        'goods_imgs'     =>  'serialize',
        'market_price'     =>  'float',
        'goods_price'     =>  'float',
        'ship_price'    =>  'float',
        'sort'    =>  'integer',
    ];
    public function getPkAttr($value,$data) {
        return $this->pk;
    }
    public function getSaleTextAttr($value,$data) {
        if ($data['is_on_sale']==1){
            return '是';
        }
        return '否';
    }
    /**
     * 计算运费
     * @param $goods_id int jifen_goods表id
     * @param $address_id int 地址表id
     * @param $goods_num int 数量
     */
    public function get_ship_price($goods_id,$address_id,$goods_num=1){
        if (empty($address_id)){
            return 0;
        }
        $goods=$this->where('goods_id',$goods_id)->find();
        //包邮
        if ($goods['ship_id']==0){
            return 0;
        }
        //地址信息
        $add=Db::name('user_address')->where('address_id',$address_id)->find();
        //物流信息
        $ship=Shipping::where('id',$goods['ship_id'])->find();
        if (empty($ship)){
            return 0;
        }
        //包邮地区
        $area=$ship['area'];
        if ($area){
            //省份&城市&地区 都必须要在包邮地区内
            if (in_array($add['pid'],$area) && in_array($add['cid'],$area) && in_array($add['did'],$area)){
                return 0;
            }
        }
        if ($goods_num<=$ship['frist_num']){
            return $ship['frist_money'];
        }
        $num=$goods_num-$ship['frist_num'];
        $xishu=ceil($num/$ship['second_num']);
        return $ship['frist_money'] + ($xishu*$ship['second_money']);
    }
}
